package org.garbagecan.hibernatestudy.m2o;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

public class Test {

	private static Logger logger = LoggerFactory.getLogger(Test.class);
	
	private static SessionFactory sessionFactory;
	
	public static void main(String[] args) throws Exception {
		init();
		test1();
		test2();
	}

	private static void test1() throws Exception {
		Session session = getSession();
		Transaction t = session.beginTransaction();
		A a = new A();
		a.setName("a");
		session.persist(a);

		B b1 = new B();
		b1.setName("b1");
		b1.setA(a);
		session.persist(b1);
			
		B b2 = new B();
		b2.setName("b2");
		b2.setA(a);
		session.persist(b2);
		
		t.commit();
		session.close();

		session = getSession();
		logger.info(session.createCriteria(A.class).list().toString());
		logger.info(session.createCriteria(B.class).list().toString());
		session.close();
	}

	private static void test2() throws Exception {
		Session session = getSession();
		Transaction t = session.beginTransaction();
		A a = new A();
		a.setName("a");
		session.persist(a);

		B b1 = new B();
		b1.setName("b1");
		b1.setA(a);
		session.persist(b1);

		B b2 = new B();
		b2.setName("b2");
		b2.setA(a);
		session.persist(b2);

		t.commit();
		session.close();

		session = getSession();
		t = session.beginTransaction();
		ListIterator<B> itB = (ListIterator<B>)session.createCriteria(B.class).list().listIterator();
		while(itB.hasNext()) {
			session.delete(itB.next());
		}
		ListIterator<A> itA = (ListIterator<A>)session.createCriteria(A.class).list().listIterator();
		while(itA.hasNext()) {
			session.delete(itA.next());
		}
		t.commit();
		logger.info(session.createCriteria(A.class).list().toString());
		logger.info(session.createCriteria(B.class).list().toString());
		session.close();
	}
	
	private static Session getSession() throws Exception {
		return sessionFactory.openSession();
	}
	
	private static void init() throws Exception {
		if (sessionFactory == null) {
			File file = new File(Test.class.getResource("/org/garbagecan/hibernatestudy/m2o/hibernate.cfg.xml").getFile());
			Configuration configuration = new Configuration().configure(file);
			sessionFactory = configuration.buildSessionFactory();
			new SchemaUpdate(configuration).execute(true, true);
		}
	}
}
